package com.jspxcms.core.web.back;

import com.jspxcms.common.orm.RowSide;
import com.jspxcms.common.web.Servlets;
import com.jspxcms.core.constant.Constants;
import com.jspxcms.core.domain.Role;
import com.jspxcms.core.domain.Site;
import com.jspxcms.core.domain.WorkflowStep;
import com.jspxcms.core.service.OperationLogService;
import com.jspxcms.core.service.RoleService;
import com.jspxcms.core.service.WorkflowService;
import com.jspxcms.core.service.WorkflowStepService;
import com.jspxcms.core.support.Context;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

import static com.jspxcms.core.constant.Constants.*;

/**
 * @author DELL
 */
@Controller
@RequestMapping("/core/workflow_step")
public class WorkflowStepController {
    private static final Logger logger = LoggerFactory.getLogger(WorkflowStepController.class);

    @Autowired
    private WorkflowStepService workflowStepService;

    @Autowired
    private WorkflowService workflowService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private OperationLogService logService;


    @RequestMapping("list.do")
    @RequiresRoles("super")
//    @RequiresPermissions("core:workflow_step:list")
    public String list(
            @PageableDefault(sort = {"seq", "id"}, direction = Sort.Direction.ASC) Pageable pageable,
            HttpServletRequest request, Integer workflowId,
            org.springframework.ui.Model modelMap) {
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
//        Integer siteId = Context.getCurrentSiteId();
        List<WorkflowStep> list = workflowStepService.findList(workflowId, params, pageable.getSort());
        modelMap.addAttribute("list", list);
        modelMap.addAttribute("workflowId", workflowId);
        return "core/workflow_step/workflow_step_list";
    }

    @RequestMapping("create.do")
    @RequiresRoles("super")
//    @RequiresPermissions("core:workflow_step:create")
    public String create(Integer id, Integer workflowId, HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite();
        WorkflowStep bean = new WorkflowStep();
        bean.setWorkflow(workflowService.get(workflowId));
        if (id != null) {
            bean = workflowStepService.get(id);
//            Backends.validateDataInSite(bean, site.getId());
        }
        modelMap.addAttribute("bean", bean);

        List<Role> roles = roleService.findList(site.getId());
        modelMap.addAttribute("roles", roles);
        modelMap.addAttribute(OPRT, CREATE);
        return "core/workflow_step/workflow_step_form";
    }

    @RequestMapping("edit.do")
    @RequiresRoles("super")
//    @RequiresPermissions("core:workflow_step:edit")
    public String edit(Integer id, Integer position,
                       @PageableDefault(sort = {"seq", "id"}, direction = Sort.Direction.ASC) Pageable pageable,
                       HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId();
        WorkflowStep bean = workflowStepService.get(id);
//        Backends.validateDataInSite(bean, siteId);
        Map<String, String[]> params = Servlets.getParamValuesMap(request,
                Constants.SEARCH_PREFIX);
        RowSide<WorkflowStep> side = workflowStepService.findSide(siteId, params, bean, position,
                pageable.getSort());
//        modelMap.addAttribute("infoPerms", bean.getInfoPerms());
//        modelMap.addAttribute("nodePerms", bean.getNodePerms());

        List<Role> roles = roleService.findList(siteId);
        modelMap.addAttribute("roles", roles);

        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute("side", side);
        modelMap.addAttribute("position", position);
        modelMap.addAttribute(OPRT, EDIT);
        return "core/workflow_step/workflow_step_form";
    }

//    @RequestMapping("export.do")
//    @RequiresRoles("super")
////    @RequiresPermissions("core:workflow_step:exportNode")
//    public void exportSite(Integer id, HttpServletResponse response) throws JAXBException, IOException {
//        Site site = service.get(id);
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("text/html;charset=utf-8");
//        File dir = sitePortService.exportAll(site);
////        List<File> list = new ArrayList<>();
////        Collections.addAll(list, dir.listFiles());
////        LocalFileHandler fileHandler = FileHandler.getLocalFileHandler(pathResolver, "");
////        list.add(fileHandler.getFile(site.getSiteBase("")));
//        response.setContentType("application/x-download;charset=UTF-8");
//        response.addHeader("Content-disposition", "filename=site_" + site.getId() + ".zip");
//        try {
//            AntZipUtils.zip(dir.listFiles(), response.getOutputStream());
//            FileUtils.deleteQuietly(dir);
//        } catch (IOException e) {
//            logger.error("zip error!", e);
//        }
//    }
//
//    @RequestMapping("import.do")
//    public String importSite(@RequestParam(value = "file", required = false) MultipartFile file,
//                             HttpServletRequest request, HttpServletResponse response, RedirectAttributes ra)
//            throws IOException, JAXBException {
//        User user = Context.getCurrentUser();
//        File tempFile = FilesEx.getTempFile();
//        file.transferTo(tempFile);
//        File unzipFile = FilesEx.getTempFile();
//        AntZipUtils.unzip(tempFile, unzipFile);
//        FileUtils.deleteQuietly(tempFile);
//        sitePortService.importAll(unzipFile, user.getId());
//        FileUtils.deleteQuietly(unzipFile);
//        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
//        return "redirect:list.do";
//    }

    @RequestMapping("save.do")
    @RequiresRoles("super")
//    @RequiresPermissions("core:workflow_step:save")
    public String save(WorkflowStep bean, Integer[] roleIds, Integer workflowId,
                       String redirect, HttpServletRequest request, RedirectAttributes ra) {

//        Integer siteId = Context.getCurrentSiteId();
        workflowStepService.save(bean, roleIds, workflowId);


//        Integer userId = Context.getCurrentUserId();
        logService.operation("opr.workflow_step.add", bean.getName(), null, bean.getId(), request);
        logger.info("save workflow_step, name={}.", bean.getName());
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do?workflowId="+workflowId;
        } else if (Constants.REDIRECT_CREATE.equals(redirect)) {
            return "redirect:create.do?workflowId="+workflowId;
        } else {
            ra.addAttribute("id", bean.getId());
            return "redirect:edit.do";
        }
    }

    @RequestMapping("update.do")
    @RequiresRoles("super")
//    @RequiresPermissions("core:workflow_step:update")
    public String update(@ModelAttribute("bean") WorkflowStep bean, Integer[] roleIds, Integer position,
                         String redirect, HttpServletRequest request, RedirectAttributes ra) {
//        Integer siteId = Context.getCurrentSiteId();
//        bean.setSite(Context.getCurrentSite());
        workflowStepService.update(bean, roleIds);

        logService.operation("opr.workflow_step.edit", bean.getName(), null, bean.getId(), request);
        logger.info("update workflow_step, name={}.", bean.getName());
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do";
        } else {
            ra.addAttribute("id", bean.getId());
            ra.addAttribute("position", position);
            return "redirect:edit.do";
        }
    }

    @RequestMapping("delete.do")
    @RequiresRoles("super")
//    @RequiresPermissions("core:workflow_step:delete")
    public String delete(Integer[] ids,HttpServletRequest request, RedirectAttributes ra) {
        Integer workflowId = 0;
        WorkflowStep[] beans = workflowStepService.delete(ids);
        for (WorkflowStep bean : beans) {
            workflowId = bean.getWorkflow().getId();
            logService.operation("opr.workflow_step.delete", bean.getName(), null, bean.getId(), request);
            logger.info("delete workflow_step, name={}.", bean.getName());
        }
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return "redirect:list.do?workflowId="+workflowId;
    }


    @ModelAttribute("bean")
    public WorkflowStep preloadBean(@RequestParam(required = false) Integer oid) {
        return oid != null ? workflowStepService.get(oid) : null;
    }
}
